﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EasyClassUI.entity;
using EasyClassUI.Utils;
using RestSharp;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace EasyClassUI.WebRequest {

    // 下载帖子时的返回信息，posts数组存储帖子，status为服务器返回值
    public class PostDownloadStatus {
        public Post[] Posts { get; set; }
        public string Status { get; set; }
    }

    /*--------------------------------------------------------------------------------*/
    /*-----------------帖子服务类------------------*/
    class PostService {
        private string postURL = "https://localhost:5001/post/";

        // 转换帖子为二进制并与帖子属性信息合并成字符串
        private string Post2Binary(string file, Post postInfo) {
            string FilePath = file;
            FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
            Byte[] body = new Byte[(int)fs.Length];
            fs.Read(body, 0, body.Length);
            fs.Close();
            postInfo.Content = body;
            string PostStr = TypeToString.PostToString(postInfo);
            return PostStr;
        }

        // 转换二进制文件流的帖子为md文件
        private bool Binary2Post(string file, Byte[] body) {
            try {
                using (var filestream = new FileStream(@$"{file}", FileMode.Create, FileAccess.Write)) {
                    filestream.Write(body, 0, body.Length);
                    return true;
                }
            }
            catch (Exception) {
                return false;
            }
        } 

        // 上传帖子
        public string UploadPost(List<string> fileToUpload, string markdownFile, Post postInfo, string Token) {
            var client = new RestClient($"{postURL}add");
            fileToUpload.Add(markdownFile); // 保存md文件时，文件名用yyyy-M-dd--HH-mm-ss.md命名
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Authorization", Token);
            Parallel.ForEach(fileToUpload, file => request.AddFile("Annex", file));
            request.AddParameter("PostString", Post2Binary(markdownFile, postInfo));
            IRestResponse response = client.Execute(request);
            string status = Convert.ToInt32(response.StatusCode).ToString();
            switch (status) {
                case "200": return "200";
                case "400": return "400";
                default: return "404";
            }
        }

        // 为帖子点赞
        public string LikePost(string PostID) {
            var client = new RestClient($"{postURL}LikeAdd?PostID={PostID}");
            client.Timeout = -1;
            var request = new RestRequest(Method.PUT);
            IRestResponse response = client.Execute(request);
            string status = Convert.ToInt32(response.StatusCode).ToString();
            switch (status) {
                case "200": return "200";
                case "400": return "400";
                default: return "404";
            }
        }

        // 查看一个帖子
        public string AddViewCount(string PostID) {
            var client = new RestClient($"{postURL}ViewNumAdd?PostID={PostID}");
            client.Timeout = -1;
            var request = new RestRequest(Method.PUT);
            IRestResponse response = client.Execute(request);
            string status = Convert.ToInt32(response.StatusCode).ToString();
            switch (status) {
                case "200": return "200";
                case "400": return "400";
                default: return "404";
            }
        }

        // 查询帖子并下载
        public string DownloadPost(string keyWord, string StudyGroupID) {
            var client = new RestClient($"{postURL}SearchByTitle?Title={keyWord}&StudyGroupID={StudyGroupID}");
            client.Timeout = -1;
            var request = new RestRequest(Method.GET);
            IRestResponse response = client.Execute(request);
            string searchResult = response.Content.ToString();
            Post[] result = JsonConvert.DeserializeObject<Post[]>(searchResult);
            if (!Directory.Exists(@".\posts\")) {
                Directory.CreateDirectory(@".\posts\");
            }

            for(int i = 0; i < result.Length; i++) {
                Binary2Post($"./posts/{result[i].PostID}.md", result[i].Content);
            }
            string status = Convert.ToInt32(response.StatusCode).ToString();
            switch (status) {
                case "200": return "200";
                case "400": return "400";
                default: return "404";
            }
        }
    }
}
